package com.ruoyi.binance.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.utils.StringUtils;

import java.io.IOException;
import java.util.Date;

public class BaseApi {

    /**
     * 测试服务器连通性
     */
    public static Boolean ping() {
        try {
            String body = HttpRequest.get(Config.BASE_URL + Config.PING_URL)
                    .timeout(20000)//超时，毫秒
                    .execute().body();
            if (StringUtils.isBlank(body)) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static Date time() {
        try {
            String body = HttpRequest.get(Config.BASE_URL + Config.TIME_URL)
                    .timeout(20000)//超时，毫秒
                    .execute().body();
            if (StringUtils.isBlank(body)) {
                return null;
            }
            Date time = JSONUtil.parseObj(body).getDate("serverTime");
            setSystemTime(time);
            return time;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    private static void setSystemTime(Date time) throws IOException {
        String os = System.getProperty("os.name").toLowerCase();
        String command = "";

        if (os.contains("win")) {
            // Windows 命令
            command = String.format("cmd /c time %tT && date %tF", time, time);
        }
        if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
            // Linux/macOS 命令
            command = "date -s \"" + time + "\"";
        }
        // 执行命令（需要管理员/root权限）
        Runtime.getRuntime().exec(command);
    }
}
